import json
import copy
from django.template import Library
from django.conf import settings
from django.urls import reverse
from django.utils.safestring import mark_safe

register = Library()


@register.inclusion_tag('tag/breadcrumb.html')
def nb_breadcrumb(request):
    permission_dict = settings.NB_PERMISSIONS[request.nb_user.role]
    url_name = request.resolver_match.url_name
    text_list = []
    current_dict = permission_dict.get(url_name)
    text_list.insert(0, {"text": current_dict['text'], 'name': url_name})
    parent = current_dict['parent']
    while parent:
        loop = permission_dict[parent]
        text_list.insert(0, {"text": loop['text'], 'name': parent})
        parent = loop['parent']
    # print(text_list)
    text_list.insert(0, {"text": '首页', 'name': 'home'})
    return {'text_list': text_list}


@register.filter
def has_permission(request, name):
    print(request, name)
    permission_dict = settings.NB_PERMISSIONS[request.nb_user.role]
    if name not in permission_dict:
        return False
    return True


@register.simple_tag
def gen_and_permission(request, name, text, *args, **kwargs):
    permission_dict = settings.NB_PERMISSIONS[request.nb_user.role]
    if name not in permission_dict:
        return ""
    url = reverse(name, args=args, kwargs=kwargs)
    print(url)
    html = f"""<a href="{url}">{text}</a>"""
    return mark_safe(html)



